package com.cysyz.mylib.mylibtools.livetelecast;

import com.cysyz.json.utils.JsonUtils;
import com.cysyz.mylib.mylibtools.httpclient.HttpRequestProxy;
import com.cysyz.mylib.utils.MyMapUtils;

import java.util.HashMap;
import java.util.Map;

public class LiveTelecastSystemEngine {
    private HttpRequestProxy httpRequestProxy;
    private String urlPrefix;
    private String loginName;
    private String password;

    public LiveTelecastSystemEngine(HttpRequestProxy httpRequestProxy, String urlPrefix, String loginName, String password) {
        this.httpRequestProxy = httpRequestProxy;
        this.urlPrefix = urlPrefix;
        this.loginName = loginName;
        this.password = password;
    }

    public <T extends LiveTelecastResponse> T execute(String urlPostfix, Class<T> returnClazz, Object... paramBeans) {
        String url = this.urlPrefix + urlPostfix;
        Map<String, String> paramsMap = new HashMap<String, String>();
        for (Object paramBean : paramBeans) {
            paramsMap.putAll(MyMapUtils.toMap(paramBean));
        }
        paramsMap.put("loginName", this.loginName);
        paramsMap.put("password", this.password);
        paramsMap.put("sec", "false");
        String responseJson = new String(httpRequestProxy.doPost(url, paramsMap));
        T response = JsonUtils.json2Bean(responseJson, returnClazz);
        checkResponse(response);
        return response;
    }

    private <T extends LiveTelecastResponse> void checkResponse(T response) {
        if (!ResponseCode.SUCCESS.getCode().equals(response.getCode())) {
            throw new LiveTelecastSystemException(response.getMessage());
        }
    }


}
